/**
 * Created by gongxun on 16/11/18.
 */

var KwxTableUILayer = GameCCSBase.extend({
    mKwxTableResultLayer : null,
    mKwxTableOperatingLayer : null,
    mKwxTablePiaoLayer : null,
    mKwxTableMicLayer : null,
    mKwxTableRecordCardLayer : null,
    mKwxTablePlayerInfoLayer : null,
    mKwxDialogSetting : null,
    mKwxDialogChat : null,
    mKwxTableMaimaLayer : null,
    mKwxTableEndLayer : null,
    mKwxApplyTableLayer : null,
    Image_players : null,
    Panel_wait : null,
    Button_ready : null,
    Button_invite : null,
    Button_jiesan : null,
    Panel_ting : null,
    mTingUIs : null,
    Panel_chats : null,
    //用户信息
    mPlayerInfos : null,
    //网络延迟
    mKwxSysInfoWidget : null,
    //踢人
    Button_kick1 : null,
    Button_kick2 : null,
    //飘
    Panel_piao : null,
    //ip提示
    Image_ipwarring : null,
    ctor : function(){
        this._super();
        this.loadCocostudio("res/ccs/KwxTableUI.json");
        this.Panel_wait = mo.seekWidgetByName(this.ccsNode, "Panel_wait");
        this.Button_ready = mo.seekWidgetByName(this.Panel_wait, "Button_ready");
        this.Button_invite = mo.seekWidgetByName(this.Panel_wait, "Button_invite");
        this.Button_jiesan = mo.seekWidgetByName(this.Panel_wait, "Button_jiesan");
        this.Panel_ting = mo.seekWidgetByName(this.ccsNode, "Panel_ting");
        this.Button_kick1 = mo.seekWidgetByName(this.ccsNode, "Button_kick1");
        this.Button_kick2 = mo.seekWidgetByName(this.ccsNode, "Button_kick2");
        this.Panel_piao = mo.seekWidgetByName(this.ccsNode, "Panel_piao");
        this.Image_ipwarring = mo.seekWidgetByName(this.ccsNode, "Image_ipwarring");

        this.mKwxTableResultLayer = new KwxTableResultLayer();
        this.addChild(this.mKwxTableResultLayer);

        this.mKwxTableOperatingLayer = new KwxTableOperatingLayer();
        this.addChild(this.mKwxTableOperatingLayer);

        this.mKwxTablePiaoLayer = new KwxTablePiaoLayer();
        this.addChild(this.mKwxTablePiaoLayer);

        if (cc.sys.isNative){
            this.mKwxTableMicLayer = new KwxTableMicLayer();
            this.addChild(this.mKwxTableMicLayer);
        }

        this.mKwxTableRecordCardLayer = new KwxTableRecordCardLayer();
        this.addChild(this.mKwxTableRecordCardLayer);

        //个人信息
        this.mKwxTablePlayerInfoLayer = new KwxTablePlayerInfoLayer();
        this.addChild(this.mKwxTablePlayerInfoLayer);

        //设置
        this.mKwxDialogSetting = new KwxDialogSetting();
        this.addChild(this.mKwxDialogSetting);

        //聊天
        this.mKwxDialogChat = new KwxDialogChat();
        this.mKwxDialogChat.setChatButton(mo.seekWidgetByName(this.ccsNode, "Button_chat"), "kwx");
        this.addChild(this.mKwxDialogChat);

        this.mKwxTableMaimaLayer = new KwxTableMaimaLayer();
        this.addChild(this.mKwxTableMaimaLayer);

        //结算
        this.mKwxTableEndLayer = new KwxTableEndLayer();
        this.addChild(this.mKwxTableEndLayer);

        //退出
        this.mKwxApplyTableLayer = new KwxApplyTableLayer("kwx");
        this.addChild(this.mKwxApplyTableLayer);

        this.loadUI();
        mo.gameHelper.fixIosText(this.ccsNode);
    },

    onEnter : function(){
        this._super();

        mo.eventHelper.add("UserChatMsgResponse", this, function(userChatMsgResponse){
            this.setChatMsg(userChatMsgResponse);
        });

        mo.eventHelper.add("UserChatMsgResponse_reward", this, function(userChatMsgResponse){
            this.setChatMsgReward(userChatMsgResponse);
        });

        mo.eventHelper.add("UserOnLineChange", this, function(onlineInfo){
            this.setPlayerOnlineStats(onlineInfo);
        });

        this.updatePiaoSelect();
        mo.eventHelper.add("gameSelectPiaoUpdate", this, function(){
            this.updatePiaoSelect();
        });

        //退出
        mo.eventHelper.add("CancleJuRequestkwx", this, function(cancleJu){
            this.mKwxApplyTableLayer.updateCancelJuInfo(cancleJu);
        });
    },

    onExit : function(){
        mo.eventHelper.remove(this);

        this._super();
    },

    setIsReplay : function(isReplay){
        mo.seekWidgetByName(this.ccsNode, "Button_chat").setVisible(!isReplay);
        mo.seekWidgetByName(this.ccsNode, "Button_setting").setVisible(!isReplay);
        mo.seekWidgetByName(this.ccsNode, "Button_return").setVisible(false);
        this.mKwxSysInfoWidget.setVisible(!isReplay);
        if (this.mKwxTableMicLayer != null){
            this.mKwxTableMicLayer.setVisible(!isReplay);
        }
    },

    loadUI : function(){
        //退出
        mo.seekWidgetByName(this.ccsNode, "Button_return").addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                if (mo.kwxTable.mPlayerType == 0){
                    mo.kwxTable.mKwxReplayLayer.onPlayEnd();
                }else{
                    this.mKwxApplyTableLayer.sendCancelTableAgree();
                }
            }
        }, this);

        //设置
        mo.seekWidgetByName(this.ccsNode, "Button_setting").addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                // if (!cc.sys.isNative){
                //     var isFull = cc.screen.fullScreen();
                //     var msg = (isFull ? "全屏" : "没有全屏");
                //     mo.showRoomMsgShow(msg);
                //
                //     cc.screen.requestFullScreen(document.getElementById("gameCanvas"));
                // }
                this.mKwxDialogSetting.setDialog(true);
            }
        }, this);

        //准备
        this.Button_ready.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                mo.gameMsgManager.sendGameReadyRequestkwx(mo.kwxCardHelper.getUseSelectPiao());
            }
        }, this);

        //邀请
        this.Button_invite.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                mo.kwxTable.onInvite();
            }
        }, this);

        //解散
        this.Button_jiesan.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                var isStart = mo.kwxTable.mTableConfig.maxpan != mo.kwxTableStatus.mTableStatus.LeftPlayTimes;
                if (!isStart){
                    mo.showMsgDialogOkAndCancel("确定退出房间吗？\n牌局未开始退出不会消耗房卡\n房主退出会解散牌桌", function(){
                        if (mo.kwxTable.mTableConfig.maxpan == mo.kwxTableStatus.mTableStatus.LeftPlayTimes){
                            mo.gameMsgManager.sendForceExitTableRequestkwx();
                        }
                    }, this, function(){}, this);
                }
            }
        }, this);

        //玩家头像
        this.Image_players = [];
        for (var i = 0; i < 3; i++){
            var Image_player = mo.seekWidgetByName(this.ccsNode, "Image_player" + i);
            this.Image_players.push(Image_player);

            Image_player.setTag(i);
            Image_player.addTouchEventListener(function(sender, type){
                if (mo.gameHelper.getIsTouchEnd(type)) {
                    var index = sender.getTag();
                    var logicSeat = mo.kwxTableStatus.getLogicForView(index, mo.kwxTableStatus.mTableStatus.MySeat - 1) + 1;
                    var seatUser = mo.kwxTableStatus.mTableStatus["SeatUser" + logicSeat];
                    if (seatUser != null){
                        this.mKwxTablePlayerInfoLayer.showPlayerInfo(index, seatUser.user_info, sender.getPosition(), logicSeat - 1);
                    }
                }
            }, this);
        }

        //听
        this.mTingUIs = [];
        for (var i = 0; i < 3; i++){
            var ting = new KwxTingUIWidget();
            ting.setTingSeat(i);
            this.Panel_ting.addChild(ting);
            ting.setVisible(false);
            this.mTingUIs.push(ting);
        }

        //聊天
        this.Panel_chats = [];
        for(var i = 0; i < 3; i++){
            var Panel_chat = mo.seekWidgetByName(this.ccsNode, "Panel_chat" + i);
            this.Panel_chats.push(Panel_chat);
            Panel_chat.setVisible(false);
        }

        //问题反馈
        if (mo.gameHelper.developerVersion == "2.0"){
            mo.seekWidgetByName(this.ccsNode, "Button_test").setVisible(false);
        }else if (mo.gameHelper.developerVersion == "3.0"){
            mo.seekWidgetByName(this.ccsNode, "Button_test").setVisible(false);
        }
        mo.seekWidgetByName(this.ccsNode, "Button_test").addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                //test
                mo.sceneMainLayer.addChild(new KwxFeedbackLayer(mo.kwxTableStatus.mTableStatus.ReplayId));
            }
        }, this);

        //踢人
        this.Button_kick1.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                this.setKickPlayerForViewSeat(1);
            }
        }, this);

        this.Button_kick2.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                this.setKickPlayerForViewSeat(2);
            }
        }, this);

        //飘
        for (var i = 0; i < 3; i++){
            var Panel_piao = mo.seekWidgetByName(this.Panel_piao, "Panel_piao" + i);
            Panel_piao.setTag(i);
            Panel_piao.addTouchEventListener(function(sender, type){
                if (mo.gameHelper.getIsTouchEnd(type)) {
                    mo.kwxCardHelper.setUserSelectPiao(sender.getTag());
                }
            }, this);
        }

        //wifi控件
        this.mKwxSysInfoWidget = new KwxSysInfoWidget();
        mo.seekWidgetByName(this.ccsNode, "Panel_wifi").addChild(this.mKwxSysInfoWidget);
    },

    setUserInfos : function(infos){
        var isSeatFull = true;
        this.mPlayerInfos = infos;

        for (var i = 0; i < 3; i++){
            var Image_player = this.Image_players[i];
            if (infos[i]){
                Image_player.setVisible(true);

                //nick
                mo.gameHelper.setTextString(mo.seekWidgetByName(Image_player, "Text_nick"), mo.gameHelper.getUserNickFilter(infos[i].user_info.nickname));

                //head
                mo.gameHelper.loadImageForUrl(mo.seekWidgetByName(Image_player, "Image_head"), infos[i].user_info.faceUrl);

                //coins
                // var ids = infos[i].user_info.items_id;
                // var nums = infos[i].user_info.items_num;
                // var coins = mo.gameUserInfo.getItemNum(ids, nums, 0);
                var Text_score = mo.seekWidgetByName(Image_player, "Text_score");
                var score = infos[i].RTScore;
                if (infos[i].RTScore == null){
                    score = infos[i].Score;
                }

                Text_score.stopAllActions();
                Text_score.setTag(score);
                if (mo.kwxTableStatus.mTableStatus.Step == 0){
                    if (Text_score.getString() == "-999"){
                        mo.gameHelper.setTextString(Text_score, score + "");
                    }else{
                        Text_score.runAction(cc.sequence(
                            cc.delayTime(4),
                            cc.callFunc(function(){
                                mo.gameHelper.setTextString(this, this.getTag());
                            }, Text_score)
                        ));
                    }
                }else{
                    mo.gameHelper.setTextString(Text_score, score + "");
                }

                //是否亮听 不在这里显示了
                // var isOpenTing = infos[i].OpenTing;
                // var Image_ting = mo.seekWidgetByName(Image_player, "Image_ting");
                // if (mo.kwxTableStatus.mTableStatus.Step == 2){
                //     Image_ting.setVisible(isOpenTing);
                // }else{
                //     Image_ting.setVisible(false);
                // }

                //是否庄家
                var isHost = infos[i].IsHost;
                mo.seekWidgetByName(Image_player, "Image_host").setVisible(isHost);

                //飘
                var piao = infos[i].Piao;
                var Image_piao = mo.seekWidgetByName(Image_player, "Image_piao");
                if (piao != null && (piao >=0 && piao <= 2)){
                    Image_piao.setVisible(true);
                    mo.gameHelper.loadTextureImage(Image_piao, "res/ccs/table/icon_piao" + piao + ".png");
                }else{
                    Image_piao.setVisible(false);
                }

                //ready
                var Image_ready = mo.seekWidgetByName(Image_player, "Image_ready");
                if (mo.kwxTableStatus.mTableStatus.Step == 0){
                    var isReady = (infos[i].State == 1);
                    Image_ready.setVisible(isReady);

                    if (i == 0){
                        this.Button_ready.setVisible(!isReady);

                        //飘的显示
                        var piaoShow = true;
                        if (isReady){
                            piaoShow = false;
                        }else if (mo.kwxTable.mTableConfig.piao == 0){
                            piaoShow = false;
                        }
                        this.Panel_piao.setVisible(piaoShow);
                    }
                }else{
                    Image_ready.setVisible(false);
                }
            }else{
                Image_player.setVisible(false);
                isSeatFull = false;
            }
        }

        this.setPlayerSeatPos(isSeatFull);
    },

    showReady : function(isShow){
        this.Panel_wait.setVisible(isShow);

        var isShowJiesan = mo.kwxTable.mTableConfig.maxpan == mo.kwxTableStatus.mTableStatus.LeftPlayTimes;
        if (isShow){
            this.Button_jiesan.setVisible(isShowJiesan);
        }
    },

    setShowKickBtn : function(isStart){
        //踢人按钮显示
        var funcShowKick = function(viewSeat){
            if (isStart){
                return false;
            }

            var logicSeat = mo.kwxTableStatus.getLogicForView(viewSeat, mo.kwxTableStatus.mTableStatus.MySeat - 1) + 1;
            return mo.kwxTable.mIsRoomCreator && mo.kwxTableStatus.mTableStatus["SeatUser" + logicSeat] != null;
        };

        this.Button_kick1.setVisible(funcShowKick(1));
        this.Button_kick2.setVisible(funcShowKick(2));

        //处理同ip显示问题
        var ipEquals = mo.kwxTableStatus.getPlayerIpEqual();
        if (ipEquals.length > 0 && !isStart){
            this.Image_ipwarring.setVisible(true);
            for (var i = 0; i < 5; i++){
                var Panel_ip = mo.seekWidgetByName(this.Image_ipwarring, "Panel_ip" + i);
                if (ipEquals.length > i){
                    Panel_ip.setVisible(true);
                    mo.gameHelper.setTextString(mo.seekWidgetByName(Panel_ip, "Text_ip_nick"), ipEquals[i].nick);
                    mo.gameHelper.setTextString(mo.seekWidgetByName(Panel_ip, "Text_ip_ip"), ipEquals[i].ip);
                }else {
                    Panel_ip.setVisible(false);
                }
            }
        }else{
            this.Image_ipwarring.setVisible(false);
        }
    },

    setShowTing : function(seat, tingNums){
        this.mTingUIs[seat].setTingCards(tingNums);
    },

    setMyShowTing : function(tingNums){
        this.mTingUIs[0].setMyTingCards(tingNums);
    },

    setChatMsg : function(userChatMsg){
        var seat = mo.kwxTableStatus.getViewSeatForUid(userChatMsg.uid);
        var showSeat = seat;
        //2人场变换位置
        if (mo.gameMsgManager.kwxGameModel == 2){
            if (seat == 1){
                showSeat = 2;
            }
        }

        var Panel_chat = this.Panel_chats[showSeat];
        Panel_chat.stopAllActions();

        var Image_chat = mo.seekWidgetByName(Panel_chat, "Image_chat");
        var Sprite_face = mo.seekWidgetByName(Panel_chat, "Sprite_face");
        var Panel_audio = mo.seekWidgetByName(Panel_chat, "Panel_audio");
        var Text_content = mo.seekWidgetByName(Panel_chat, "Text_content");

        Panel_chat.setVisible(false);
        Image_chat.setVisible(false);
        Sprite_face.setVisible(false);
        Panel_audio.setVisible(false);
        Text_content.setVisible(false);

        if (userChatMsg.type == 1){
            //处理文字消息
            var numIndex = parseInt(userChatMsg.msg);

            if (numIndex >=0 && numIndex < 13){
                //播放音效
                var sex = mo.kwxTableStatus.getSexForUid(userChatMsg.uid);
                mo.soundHelper.playUserCustom(sex, numIndex);

                //快捷短语
                Text_content.setVisible(true);
                mo.gameHelper.setTextString(Text_content, mo.gameUserInfo.userCustomText[numIndex]);
                var sizeW = Text_content.getContentSize().width + 40;
                sizeW = Math.max(sizeW, 70);
                Text_content.setPositionX(sizeW / 2);

                Panel_chat.setVisible(true);
                Image_chat.setVisible(true);
                Image_chat.setContentSize(cc.size(sizeW, 64));

                Panel_chat.runAction(
                    cc.sequence(
                        cc.delayTime(3.0),
                        cc.hide()
                    )
                );
            }else if (numIndex >= 51 && numIndex < 80){

                //表情
                Sprite_face.setVisible(true);
                var animation = new cc.Animation(mo.kwxCardHelper.getFaceFrames(numIndex - 51));
                animation.setDelayPerUnit(0.2);
                Sprite_face.stopAllActions();
                Sprite_face.runAction(cc.repeatForever(cc.animate(animation)));

                Panel_chat.setVisible(true);

                Panel_chat.runAction(
                    cc.sequence(
                        cc.delayTime(3.0),
                        cc.hide(),
                        cc.callFunc(function(){
                            Sprite_face.stopAllActions();
                        }, Panel_chat)
                    )
                );
            }else{
                Panel_chat.setVisible(false);

                var formSeat = seat;
                var toSeat = mo.kwxTableStatus.getViewForLogic(numIndex % 10, mo.kwxTableStatus.mTableStatus.MySeat - 1);
                var index = (parseInt(numIndex / 10) % 10);
                var p1 = this.Image_players[formSeat].getPosition();
                var p2 = this.Image_players[toSeat].getPosition();

                this.mKwxTablePlayerInfoLayer.showEffectChat(formSeat, toSeat, index, p1, p2);
            }
        }else{
            if (!cc.sys.isNative){
                return;
            }

            //语音
            Panel_audio.setVisible(true);

            Panel_chat.setVisible(true);
            Image_chat.setVisible(true);
            Image_chat.setContentSize(cc.size(70, 64));

            //语音信息
            var intArray = [];
            var vmsg = userChatMsg.vmsg;
            var lenght = vmsg.limit - vmsg.offset;
            for (var i = 0; i < lenght; i++){
                intArray.push(vmsg.view[i + vmsg.offset]);
            }

            var millisecond = mo.gameHelper.getMillisecond().toString();
            var fileName = millisecond + ".amr";
            mo.nativeHelper.playFile(fileName, intArray);

            var time = (lenght / 1500);
            Panel_chat.runAction(
                cc.sequence(
                    cc.delayTime(time),
                    cc.hide()
                )
            );
        }
    },

    setPlayerSeatPos : function(isSeatFull){
        this.Button_invite.setVisible(!isSeatFull);
    },

    //设置离线状态
    setPlayerOnlineStats : function(onlineInfo){
        //重置
        for (var i = 0; i < 3; i++) {
            var Image_player = this.Image_players[i];
            mo.seekWidgetByName(Image_player, "Image_online").setVisible(false);
        }

        //设置状态
        if (this.mPlayerInfos != null){
            for (var i = 0; i < 3; i++) {
                if (this.mPlayerInfos[i] == null){
                    continue;
                }
                var Image_player = this.Image_players[i];
                var uid = this.mPlayerInfos[i].user_info.userid;

                if (onlineInfo[uid.toString()] != undefined && onlineInfo[uid.toString()] == 0){
                    mo.seekWidgetByName(Image_player, "Image_online").setVisible(true);
                }
            }
        }
    },

    //踢人
    setKickPlayerForViewSeat : function(viewSeat){
        var logicSeat = mo.kwxTableStatus.getLogicForView(viewSeat, mo.kwxTableStatus.mTableStatus.MySeat - 1) + 1;
        var SeatUser = mo.kwxTableStatus.mTableStatus["SeatUser" + logicSeat];
        if (SeatUser != null){
            mo.showMsgDialogOkAndCancel("确定要踢掉玩家[" + SeatUser.user_info.nickname + "]吗?", function(){
                mo.gameMsgManager.sendCreateUserKickOutRequestkwx(SeatUser.user_info.userid);
            }, this, function(){}, this);
        }
    },

    updatePiaoSelect : function(){
        var selectIndex = mo.kwxCardHelper.selectPiaoIndex;
        for (var i = 0; i < 3; i++){
            var Panel_piao = mo.seekWidgetByName(this.Panel_piao, "Panel_piao" + i);
            var Image_check = mo.seekWidgetByName(Panel_piao, "Image_check");
            Image_check.loadTexture(selectIndex == i ? "res/ccs/table/btn/check_select1.png" : "res/ccs/table/btn/check_select0.png");
        }
    },

    //礼包
    setChatMsgReward : function(userChatMsg){
        var kwxRewardLayer = new KwxRewardLayer();
        this.addChild(kwxRewardLayer);
        var toPlayer = mo.kwxTableStatus.getViewSeatForUid(userChatMsg.uid);
        if (toPlayer == -1){
            return
        }
        kwxRewardLayer.startAction(userChatMsg.msg, this.Image_players[toPlayer].getPosition(), toPlayer);
    }
});
